//
//  WBHomeTableViewController.swift
//  微博(swift)
//
//  Created by 汤米 on 16/4/17.
//  Copyright © 2016年 汤米. All rights reserved.
//

import UIKit

private let HomeTableViewCellId = "HomeTableViewCellId"

class WBHomeTableViewController: WBVisitorTableViewController {

    // MARK: -  模型数组
    var dataModels: [WBStatusModel] = [WBStatusModel]()
    
    
    override func viewDidLoad() {
        
        if !isLogin {
            
            visitorView?.setImageinfo(nil, title: nil)
            return
        }
        
        registerHomeTableViewCell()
        
        setUpUI()
        
        // MARK: -  请求首页数据
        loadHomeData(downIndicatorView.isAnimating())
        
    }
    
    // MARK: -  设置UI
    private func setUpUI() {
        
        //设置显示微博条数文字label  将label添加到navigationController的view上
        navigationController?.view.insertSubview(countLabel, belowSubview: (navigationController?.navigationBar)!)
        countLabel.frame = CGRect(x: 0, y: 64-34, width: kScreenW, height: 34)
        
        
        //设置下拉刷新
        tableView.addSubview(refresh)
        //下拉刷新控件值改变的事件
        refresh.addTarget(self, action: "refreshChange", forControlEvents: UIControlEvents.ValueChanged)
        
        //设置footView
        tableView.tableFooterView = downIndicatorView
    }
    
    // MARK: -  下拉刷新控件值改变的事件
    @objc private func refreshChange() {
        
        loadHomeData(downIndicatorView.isAnimating())
    }
    
    // MARK: -  注册tableviewcell
    private func registerHomeTableViewCell() {
        
        
        tableView.registerClass(WBHomeTableViewCell.self, forCellReuseIdentifier: HomeTableViewCellId)
        // UITableViewAutomaticDimension 自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        
        // 设置风格
        tableView.separatorStyle = .None
        
        // 预估行高 预估行高与我们实际的cell高度越接近越好
        tableView.estimatedRowHeight = 200
   
        
    }
    
    // MARK: -  懒加载显示加载了多少条数据的label
    private lazy var countLabel: UILabel = {
        
        let countLabel = UILabel()
        countLabel.textAlignment = .Center
        countLabel.textColor = UIColor.whiteColor()
        countLabel.backgroundColor = themeColor
        countLabel.hidden = true
        countLabel.font = UIFont.systemFontOfSize(14)
        return countLabel
    }()
    
    // MARK: -  懒加载系统的下拉刷新控件
    private lazy var refresh: WBRefreshControl = WBRefreshControl()
    
    // MARK: -  懒加载上滑刷新菊花
    private lazy var downIndicatorView: UIActivityIndicatorView = {
        
        let downIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        downIndicatorView.color = UIColor.grayColor()
        return downIndicatorView
        
        }()
}



// MARK: -  设置tableView界面的分类
extension WBHomeTableViewController {
    
    // MARK: -  设置cell的样子
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeTableViewCellId, forIndexPath: indexPath) as! WBHomeTableViewCell
        cell.status = dataModels[indexPath.row]
        
        return cell
    }
    
    // MARK: -  设置cell的个数
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataModels.count
    }
    
    // MARK: -  即将展示tableView某一行cell时
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.row == dataModels.count - 1 && !downIndicatorView.isAnimating() {
            
            //设置动画
            downIndicatorView.startAnimating()
            loadHomeData(downIndicatorView.isAnimating())
        }
    }
    
}

// MARK: -  请求首页数据的分类
extension WBHomeTableViewController {
    
    // MARK: -  请求微博首页数据
    func loadHomeData(isPullUp: Bool) {
        
        var sinceId: Int64 = 0
        var maxId: Int64 = 0
        
        if isPullUp {
            
            sinceId = 0
            maxId = dataModels.last?.id ?? 0
            if maxId > 0 {
                maxId = maxId - 1
            }
        }else {
            
            maxId = 0
            sinceId = dataModels.first?.id ?? 0
        }
        
        
        TMNetWorkTools.sharedTool.loadHomeData(WBUserAccountTool.sharedAccountTool.accessToken!, since_id: sinceId, max_id: maxId) { (response, error) -> () in
            
            self.endRefresh()
            
            if error != nil {
                print("错误\(error)")
                return
            }
            
            guard let array = response?["statuses"] as? [[String: AnyObject]] else {
                print("返回的不是一个数组")
                return
            }
            
            var tempArray: [WBStatusModel] = [WBStatusModel]()
            for dataDict in array {
                
                let status = WBStatusModel(dict: dataDict)
                tempArray.append(status)
            }
            
            if isPullUp {
                
                self.dataModels = self.dataModels + tempArray
                
            }else {
                
                self.dataModels = tempArray + self.dataModels
                self.countLabel.hidden = false
                self.setCountLabelAnimate(tempArray.count)
            }
            
            self.tableView.reloadData()
        }
    }
    
    // MARK: -  设置countLabel显示的文字以及动画
    func setCountLabelAnimate(count: Int) {
        
        var countString = ""
        
        if count == 0{
            countString = "您已经是最新的微博了"
        }else{
            countString = "您更新了\(count)条微博"
        }
        
        countLabel.text = countString
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            
            self.countLabel.frame.origin.y = 64
            }) { (_) -> Void in
                
                UIView.animateWithDuration(1.5, animations: { () -> Void in
                    
                    self.countLabel.frame.origin.y = 64 - 34
                    }, completion: { (_) -> Void in
                        
                        self.countLabel.hidden = true
                })
        }
    }
    

    // MARK: -  刷新控件停止转动
    private func endRefresh() {
        
        downIndicatorView.stopAnimating()
        refresh.endRefreshing()
    }
    
}
